// IPC 处理器
const { ipcMain, dialog, shell } = require('electron');
const claudeService = require('../services/claude-service');
const storageService = require('../services/storage-service');
const windowManager = require('../utils/window-manager');

/**
 * 注册所有 IPC 处理器
 */
function registerIpcHandlers() {
    // 检查 Claude Code 状态
    ipcMain.handle('claude:check-code', async () => {
        try {
            const isInstalled = await claudeService.checkClaudeCode();
            return { success: true, installed: isInstalled };
        } catch (error) {
            return { success: false, message: error.message, installed: false };
        }
    });

    // 获取详细的 Claude Code 信息
    ipcMain.handle('claude:get-info', async () => {
        try {
            const info = await claudeService.getClaudeCodeInfo();
            return { success: true, info };
        } catch (error) {
            return { success: false, message: error.message };
        }
    });

    // 获取 Claude Code 版本
    ipcMain.handle('claude:get-version', async () => {
        try {
            const version = await claudeService.getClaudeCodeVersion();
            return { success: true, version };
        } catch (error) {
            return { success: false, message: error.message };
        }
    });

    // 测试 Claude Code 检测器
    ipcMain.handle('claude:test-detector', async () => {
        try {
            console.log("[IPC] 调用 claudeService.testDetector");
            const result = await claudeService.testDetector();
            console.log("[IPC] claudeService.testDetector 结果:", JSON.stringify(result, null, 2));
            return { success: true, result };
        } catch (error) {
            return { success: false, message: error.message };
        }
    });

    // 安装 Claude Code
    ipcMain.handle('claude:install-code', async () => {
        try {
            const choice = await dialog.showMessageBox(windowManager.getMainWindow(), {
                type: 'question',
                buttons: ['是', '否'],
                defaultId: 0,
                message: '安装 Claude Code',
                detail: '是否要继续安装 Claude Code？'
            });
            
            if (choice.response === 0) {
                // 这里可以执行实际的安装逻辑
                return { success: true, message: 'Claude Code 安装成功！' };
            }
            return { success: false, message: '用户取消了安装' };
        } catch (error) {
            return { success: false, message: `安装失败: ${error.message}` };
        }
    });

    // 执行任务
    ipcMain.handle('claude:execute-task', async (event, { apiKey, task, model }) => {
        console.log("🚀 ~ registerIpcHandlers ~ apiKey:", apiKey)
        if (!apiKey || !task) {
            return {
                success: false,
                message: '缺少必要参数：API Key 和任务描述'
            };
        }

        try {
            const result = await claudeService.executeTask(apiKey, task, model);
            
            // 保存到历史记录
            if (result.success) {
                await storageService.saveTaskHistory({
                    task,
                    model,
                    result: result.result,
                    success: true
                });
            } else {
                await storageService.saveTaskHistory({
                    task,
                    model,
                    error: result.message,
                    success: false
                });
            }
            
            return result;
        } catch (error) {
            return { success: false, message: error.message };
        }
    });

    // 保存 API Key
    ipcMain.handle('storage:save-api-key', async (event, apiKey) => {
        return await storageService.saveApiKey(apiKey);
    });

    // 加载 API Key
    ipcMain.handle('storage:load-api-key', async () => {
        return await storageService.loadApiKey();
    });

    // 保存模型配置（包含 provider, model, apiKey, baseURL）
    ipcMain.handle('storage:save-model-config', async (event, modelConfig) => {
        return await storageService.saveModelConfig(modelConfig);
    });

    // 加载模型配置
    ipcMain.handle('storage:load-model-config', async () => {
        return await storageService.loadModelConfig();
    });

    // 验证 API Key
    ipcMain.handle('claude:validate-api-key', async (event, apiKey) => {
        return await claudeService.validateApiKey(apiKey);
    });

    // 获取任务历史（兼容旧API）
    ipcMain.handle('storage:get-task-history', async (event, limit) => {
        return await storageService.getTaskHistory(limit);
    });

    // 保存工作路径任务历史
    ipcMain.handle('storage:save-workspace-task', async (event, { workPath, taskData }) => {
        return await storageService.saveWorkspaceTaskHistory(workPath, taskData);
    });

    // 获取指定工作路径的任务历史
    ipcMain.handle('storage:get-workspace-history', async (event, { workPath, limit }) => {
        return await storageService.getWorkspaceTaskHistory(workPath, limit);
    });

    // 获取所有工作路径列表
    ipcMain.handle('storage:get-workspace-list', async () => {
        return await storageService.getWorkspaceList();
    });

    // 获取工作区列表（用于历史记录页面）
    ipcMain.handle('storage:get-workspace-list-stats', async () => {
        return await storageService.getWorkspaceListWithStats();
    });

    // 清除指定工作路径的历史
    ipcMain.handle('storage:clear-workspace-history', async (event, workPath) => {
        return await storageService.clearWorkspaceHistory(workPath);
    });

    // 清除所有历史记录
    ipcMain.handle('storage:clear-all-history', async () => {
        return await storageService.clearAllHistory();
    });

    // 清理缓存
    ipcMain.handle('storage:clear-cache', async () => {
        return await storageService.clearCache();
    });

    // 应用信息
    ipcMain.handle('app:get-info', async () => {
        const { app } = require('electron');
        return {
            name: app.getName(),
            version: app.getVersion(),
            platform: process.platform
        };
    });

    // 检测应用更新
    ipcMain.handle('app:check-update', async () => {
        try {
            const { app } = require('electron');
            const axios = require('axios');
            
            const currentVersion = app.getVersion();
            console.log('[IPC] 当前版本:', currentVersion);
            
            // 从 GitHub Releases 检测最新版本
            // TODO: 替换为你的实际仓库地址
            const repoUrl = 'https://api.github.com/repos/your-username/claude-code-agent/releases/latest';
            
            try {
                const response = await axios.get(repoUrl, {
                    timeout: 10000,
                    headers: {
                        'Accept': 'application/vnd.github.v3+json'
                    }
                });
                
                const latestVersion = response.data.tag_name.replace(/^v/, ''); // 移除 v 前缀
                const changelog = response.data.body || '暂无更新说明';
                const downloadUrl = response.data.html_url;
                
                console.log('[IPC] 最新版本:', latestVersion);
                console.log('[IPC] 下载地址:', downloadUrl);
                
                // 比较版本号
                const hasUpdate = compareVersions(latestVersion, currentVersion) > 0;
                
                return {
                    success: true,
                    hasUpdate: hasUpdate,
                    currentVersion: currentVersion,
                    latestVersion: latestVersion,
                    changelog: changelog,
                    downloadUrl: downloadUrl
                };
            } catch (error) {
                // GitHub API 请求失败，可能是网络问题或仓库不存在
                console.error('[IPC] 检测更新失败:', error.message);
                
                // 返回模拟数据（开发时使用）
                return {
                    success: true,
                    hasUpdate: false,
                    currentVersion: currentVersion,
                    latestVersion: currentVersion,
                    changelog: '当前已是最新版本',
                    message: '无法连接到更新服务器，显示本地版本信息'
                };
            }
        } catch (error) {
            console.error('[IPC] 检测更新异常:', error);
            return {
                success: false,
                message: error.message
            };
        }
    });

    // 比较版本号的辅助函数
    function compareVersions(v1, v2) {
        const parts1 = v1.split('.').map(Number);
        const parts2 = v2.split('.').map(Number);
        
        for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
            const p1 = parts1[i] || 0;
            const p2 = parts2[i] || 0;
            
            if (p1 > p2) return 1;
            if (p1 < p2) return -1;
        }
        
        return 0;
    }

    // 无头模式执行 Claude
    ipcMain.handle('claude:execute-headless', async (event, { apiKey, task }) => {
        if (!apiKey || !task) {
            return {
                success: false,
                error: '缺少必要参数：API Key 和任务描述'
            };
        }

        try {
            const result = await claudeService.executeClaudeHeadless(apiKey, task);
            return result;
        } catch (error) {
            return { 
                success: false, 
                error: error.message,
                source: 'error'
            };
        }
    });

    // 测试 API 连接（强制使用传入的 API Key，不使用存储的配置）
    ipcMain.handle('claude:test-connection', async (event, { apiKey, task }) => {
        console.log('[IPC] claude:test-connection 被调用');
        console.log('[IPC] 参数:', {
            hasApiKey: !!apiKey,
            apiKeyLength: apiKey ? apiKey.length : 0,
            apiKeyPreview: apiKey ? '***' + apiKey.slice(-4) : 'none',
            task: task
        });

        if (!apiKey || !task) {
            console.error('[IPC] 缺少必要参数');
            return {
                success: false,
                error: '缺少必要参数：API Key 和任务描述',
                output: '缺少必要参数：API Key 和任务描述'
            };
        }

        try {
            console.log('[IPC] 调用 claudeService.executeClaudeHeadlessForTest...');
            const result = await claudeService.executeClaudeHeadlessForTest(apiKey, task);
            console.log('[IPC] executeClaudeHeadlessForTest 返回结果:', JSON.stringify(result, null, 2));
            return result;
        } catch (error) {
            console.error('[IPC] executeClaudeHeadlessForTest 异常:', error);
            console.error('[IPC] 错误堆栈:', error.stack);
            return { 
                success: false, 
                error: error.message,
                output: error.message,
                source: 'error'
            };
        }
    });

    // 启动 Claude 会话
    ipcMain.handle('claude:start-session', async (event, { apiKey, workPath }) => {
        console.log('[IPC] 启动 Claude 会话:', { 
            hasApiKey: !!apiKey,
            workPath 
        });
        
        if (!apiKey || !workPath) {
            return {
                success: false,
                error: '缺少必要参数：API Key 和工作路径'
            };
        }

        try {
            const result = await claudeService.startClaudeSession(apiKey, workPath);
            return result;
        } catch (error) {
            console.error('[IPC] 启动 Claude 会话失败:', error);
            return { 
                success: false, 
                error: error.message
            };
        }
    });

    // 使用会话执行任务（支持流式输出）
    ipcMain.handle('claude:execute-with-session', async (event, { task }) => {
        console.log('[IPC] 使用会话执行任务（流式）:', { 
            taskLength: task?.length 
        });
        
        if (!task) {
            return {
                success: false,
                error: '缺少任务描述'
            };
        }

        try {
            // 使用流式回调
            const result = await claudeService.executeWithSession(task, (streamData) => {
                // 实时发送流式数据到渲染进程
                event.sender.send('claude:stream-data', streamData);
            });
            
            // 发送完成信号
            event.sender.send('claude:stream-complete', result);
            
            return result;
        } catch (error) {
            console.error('[IPC] 执行任务失败:', error);
            
            // 发送错误信号
            event.sender.send('claude:stream-error', { error: error.message });
            
            return { 
                success: false, 
                error: error.message,
                source: 'error'
            };
        }
    });

    // 停止 Claude 会话
    ipcMain.handle('claude:stop-session', async () => {
        console.log('[IPC] 停止 Claude 会话');
        
        try {
            await claudeService.stopClaudeSession();
            return { success: true };
        } catch (error) {
            console.error('[IPC] 停止会话失败:', error);
            return { 
                success: false, 
                error: error.message
            };
        }
    });

    // 系统 Claude Code 执行（保持向后兼容）
    ipcMain.handle('claude:execute-system', async (event, { apiKey, task, workPath }) => {
        console.log('[IPC] 执行系统 Claude:', { 
            hasApiKey: !!apiKey,
            apiKey: apiKey ? '***' + apiKey.slice(-4) : 'none',
            task: task ? task.substring(0, 50) + '...' : 'none',
            workPath 
        });
        
        if (!apiKey || !task) {
            return {
                success: false,
                error: '缺少必要参数：API Key 和任务描述'
            };
        }

        try {
            // 如果提供了工作路径，在该路径下执行
            const result = await claudeService.executeSystemClaude(apiKey, task, workPath);
            return result;
        } catch (error) {
            console.error('[IPC] 执行系统 Claude 失败:', error);
            return { 
                success: false, 
                error: error.message,
                source: 'error'
            };
        }
    });

    // 文件系统相关处理器
    
    // 选择文件夹
    ipcMain.handle('fs:select-folder', async () => {
        try {
            const mainWindow = windowManager.getMainWindow();
            if (!mainWindow) {
                return {
                    success: false,
                    error: '无法获取主窗口'
                };
            }

            const result = await dialog.showOpenDialog(mainWindow, {
                properties: ['openDirectory'],
                title: '选择工作文件夹',
                buttonLabel: '选择此文件夹'
            });

            if (result.canceled || !result.filePaths || result.filePaths.length === 0) {
                return {
                    success: false,
                    canceled: true,
                    message: '用户取消了选择'
                };
            }

            const selectedPath = result.filePaths[0];
            console.log('[IPC] 用户选择的文件夹:', selectedPath);

            return {
                success: true,
                path: selectedPath
            };
        } catch (error) {
            console.error('[IPC] 选择文件夹失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    });

    // 打开文件夹位置
    ipcMain.handle('fs:open-folder-location', async (event, folderPath) => {
        try {
            if (!folderPath) {
                return {
                    success: false,
                    error: '未提供文件夹路径'
                };
            }

            console.log('[IPC] 打开文件夹位置:', folderPath);
            
            // 使用 shell.openPath 打开文件夹
            const errorMessage = await shell.openPath(folderPath);
            
            if (errorMessage) {
                console.error('[IPC] 打开文件夹失败:', errorMessage);
                return {
                    success: false,
                    error: `无法打开文件夹: ${errorMessage}`
                };
            }

            return {
                success: true,
                message: '已打开文件夹'
            };
        } catch (error) {
            console.error('[IPC] 打开文件夹异常:', error);
            return {
                success: false,
                error: error.message
            };
        }
    });

    // 打开终端并启动 Claude
    ipcMain.handle('terminal:open-with-claude', async (event, { workPath, apiKey }) => {
        try {
            const { exec } = require('child_process');
            const path = require('path');
            const os = require('os');
            
            if (!workPath || !apiKey) {
                return {
                    success: false,
                    error: '缺少必要参数'
                };
            }

            console.log('[IPC] 打开终端并启动 Claude:', {
                workPath,
                platform: process.platform
            });

            // 获取配置
            const config = await storageService.loadModelConfig();
            const baseURL = config?.config?.baseURL || 'https://api.deepseek.com/anthropic';

            // 根据操作系统选择不同的命令
            let command;
            
            if (process.platform === 'darwin') {
                // macOS - 使用 AppleScript 打开 Terminal.app
                // 创建临时 shell 脚本
                const fs = require('fs');
                const shellScript = `#!/bin/bash
cd "${workPath}"
export ANTHROPIC_AUTH_TOKEN="${apiKey}"
export ANTHROPIC_BASE_URL="${baseURL}"
export CLAUDE_AUTO_APPROVE="true"
clear
echo "🚀 Claude 命令行模式已启动"
echo "📂 工作目录: ${workPath}"
echo "💡 提示: 直接输入 claude \\"你的任务\\" 来执行任务"
echo ""
claude
`;
                
                const tempScriptPath = path.join(os.tmpdir(), `claude-terminal-${Date.now()}.sh`);
                fs.writeFileSync(tempScriptPath, shellScript, 'utf8');
                fs.chmodSync(tempScriptPath, '755'); // 添加执行权限
                
                // 使用 AppleScript 打开 Terminal 并执行脚本
                const appleScript = `tell application "Terminal"
    activate
    do script "${tempScriptPath}"
end tell`;
                
                command = `osascript -e '${appleScript.replace(/'/g, "\\'")}'`;
                
            } else if (process.platform === 'win32') {
                // Windows - 使用 start 打开 cmd 或 PowerShell
                const batScript = `
@echo off
cd /d "${workPath}"
set ANTHROPIC_AUTH_TOKEN=${apiKey}
set ANTHROPIC_BASE_URL=${baseURL}
set CLAUDE_AUTO_APPROVE=true
cls
echo 🚀 Claude 命令行模式已启动
echo 📂 工作目录: ${workPath}
echo 💡 提示: 直接输入 claude "你的任务" 来执行任务
echo.
claude
                `.trim();

                // 创建临时批处理文件
                const fs = require('fs');
                const tempBatPath = path.join(os.tmpdir(), `claude-terminal-${Date.now()}.bat`);
                fs.writeFileSync(tempBatPath, batScript, 'utf8');
                
                command = `start cmd.exe /K "${tempBatPath}"`;
                
            } else if (process.platform === 'linux') {
                // Linux - 尝试常见的终端模拟器
                const terminals = [
                    'gnome-terminal',
                    'konsole',
                    'xfce4-terminal',
                    'xterm'
                ];
                
                const bashScript = `
cd '${workPath}'
export ANTHROPIC_AUTH_TOKEN='${apiKey}'
export ANTHROPIC_BASE_URL='${baseURL}'
export CLAUDE_AUTO_APPROVE='true'
clear
echo '🚀 Claude 命令行模式已启动'
echo '📂 工作目录: ${workPath}'
echo '💡 提示: 直接输入 claude "你的任务" 来执行任务'
echo ''
claude
                `.trim();
                
                // 尝试找到可用的终端
                for (const terminal of terminals) {
                    try {
                        const { exec: execSync } = require('child_process');
                        execSync(`which ${terminal}`);
                        command = `${terminal} -- bash -c "${bashScript.replace(/"/g, '\\"')}"`;
                        break;
                    } catch (e) {
                        continue;
                    }
                }
                
                if (!command) {
                    return {
                        success: false,
                        error: '未找到可用的终端模拟器'
                    };
                }
            } else {
                return {
                    success: false,
                    error: `不支持的操作系统: ${process.platform}`
                };
            }

            console.log('[IPC] 执行终端命令');
            
            // 执行命令（不等待完成）
            exec(command, (error) => {
                if (error) {
                    console.error('[IPC] 打开终端出错:', error);
                } else {
                    console.log('[IPC] 终端已打开');
                }
            });

            return {
                success: true,
                message: '终端已打开'
            };
            
        } catch (error) {
            console.error('[IPC] 打开终端异常:', error);
            return {
                success: false,
                error: error.message
            };
        }
    });

    // 检测 Claude 是否可用并初始化
    ipcMain.handle('claude:check-availability', async (event, workPath) => {
        try {
            const { exec } = require('child_process');
            const util = require('util');
            const fs = require('fs');
            const path = require('path');
            const execPromise = util.promisify(exec);

            console.log('[IPC] 检测 Claude 可用性，工作路径:', workPath);

            if (!workPath || !fs.existsSync(workPath)) {
                return {
                    success: false,
                    available: false,
                    error: '工作路径不存在'
                };
            }

            // 检测 claude 命令是否存在
            try {
                const { stdout } = await execPromise('which claude', {
                    cwd: workPath,
                    timeout: 5000
                });

                if (!stdout || !stdout.trim()) {
                    return {
                        success: false,
                        available: false,
                        error: 'Claude 命令未找到'
                    };
                }

                const claudePath = stdout.trim();
                console.log('[IPC] Claude 命令路径:', claudePath);

                // 获取 Claude 版本
                let version = 'unknown';
                try {
                    const { stdout: versionOutput } = await execPromise('claude --version', {
                        cwd: workPath,
                        timeout: 5000
                    });
                    version = versionOutput.trim();
                    console.log('[IPC] Claude 版本:', version);
                } catch (versionError) {
                    console.warn('[IPC] 无法获取 Claude 版本:', versionError.message);
                }

                // 创建 Claude 配置文件以启用自动批准
                const claudeConfigDir = path.join(workPath, '.claude');
                const claudeConfigFile = path.join(claudeConfigDir, 'config.json');
                
                try {
                    // 确保 .claude 目录存在
                    if (!fs.existsSync(claudeConfigDir)) {
                        fs.mkdirSync(claudeConfigDir, { recursive: true });
                        console.log('[IPC] 创建 Claude 配置目录:', claudeConfigDir);
                    }

                    // 写入配置文件，启用自动批准
                    const config = {
                        autoApprove: true,
                        autoApproveFileCreation: true,
                        autoApproveFileModification: true,
                        autoApproveCommandExecution: false, // 命令执行仍需手动确认，更安全
                        workingDirectory: workPath
                    };

                    fs.writeFileSync(claudeConfigFile, JSON.stringify(config, null, 2));
                    console.log('[IPC] Claude 配置已创建:', claudeConfigFile);
                } catch (configError) {
                    console.warn('[IPC] 创建 Claude 配置失败:', configError.message);
                    // 配置创建失败不影响主流程
                }

                // 尝试启动 Claude（测试连接）
                // 使用 echo 命令测试 Claude 是否能正常响应
                try {
                    const testCommand = `cd "${workPath}" && echo "test" | timeout 10 claude --version 2>&1 || claude --version 2>&1`;
                    const { stdout: testOutput, stderr: testError } = await execPromise(testCommand, {
                        timeout: 15000,
                        env: {
                            ...process.env,
                            CLAUDE_AUTO_APPROVE: 'true',
                            CLAUDE_WORKING_DIR: workPath
                        }
                    });

                    console.log('[IPC] Claude 测试输出:', testOutput);
                    if (testError) {
                        console.log('[IPC] Claude 测试错误:', testError);
                    }

                    return {
                        success: true,
                        available: true,
                        version: version,
                        workPath: workPath,
                        claudePath: claudePath,
                        message: 'Claude 已准备就绪，自动批准已启用'
                    };
                } catch (testError) {
                    console.warn('[IPC] Claude 测试失败:', testError.message);
                    // 即使测试失败，只要命令存在就认为可用
                    return {
                        success: true,
                        available: true,
                        version: version,
                        workPath: workPath,
                        claudePath: claudePath,
                        message: 'Claude 已找到（测试连接失败）'
                    };
                }
            } catch (whichError) {
                console.error('[IPC] Claude 命令检测失败:', whichError.message);
                return {
                    success: false,
                    available: false,
                    error: 'Claude 命令未安装或不在 PATH 中'
                };
            }
        } catch (error) {
            console.error('[IPC] 检测 Claude 可用性异常:', error);
            return {
                success: false,
                available: false,
                error: error.message
            };
        }
    });

    console.log('[IPC] 所有处理器已注册');
}

module.exports = { registerIpcHandlers };
